package io.renren.modules.poschangerecord.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.modules.matlist.controller.TrustAllHttpsCertificates;
import io.renren.modules.poschangerecord.entity.PoschangeData;
import io.renren.modules.poschangerecord.entity.PreposEntity;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.poschangerecord.dao.PoschangerecordtableDao;
import io.renren.modules.poschangerecord.entity.PoschangerecordtableEntity;
import io.renren.modules.poschangerecord.service.PoschangerecordtableService;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service("poschangerecordtableService")
public class PoschangerecordtableServiceImpl extends ServiceImpl<PoschangerecordtableDao, PoschangerecordtableEntity> implements PoschangerecordtableService {

    @Autowired
    PoschangerecordtableDao poschangerecordtableDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String mtype =(String) params.get("key");//模糊查询
        boolean blank = StringUtils.isBlank(mtype);
        QueryWrapper<PoschangerecordtableEntity> queryWrapper;
        if(blank){
            queryWrapper = new QueryWrapper<PoschangerecordtableEntity>();
        }else{
            queryWrapper = new QueryWrapper<PoschangerecordtableEntity>().like("mtype",mtype);
        }
        IPage<PoschangerecordtableEntity> page = this.page(
                new Query<PoschangerecordtableEntity>().getPage(params),//分页工具
                queryWrapper
//                new QueryWrapper<UserinfoEntity>().like("user_name",username)
        );

        return new PageUtils(page);
    }

    @Override
    public void selectByMatid(String matid, Page<PoschangerecordtableEntity> page) {
        System.out.println(poschangerecordtableDao.selectByMatid(matid,page));
        poschangerecordtableDao.selectByMatid(matid,page);

    }

    public  List<Mat> selectByMatid(String matid) {

        List<Mat> res=new ArrayList<>();
        selectByMatid(matid,res);
        for (Mat re : res) {
            System.out.println(re);
            // cha  shu  ju  ku
        }
        return res;
    }

    @Override
    public List<PreposEntity> getPre(String matid) {
        System.out.println(poschangerecordtableDao.getPre(matid));
        return poschangerecordtableDao.getPre(matid);
    }

    @Override
    public void listselect(String mtype, Page<PoschangerecordtableEntity> page) {
        poschangerecordtableDao.listselect(mtype,page);
    }

    // 在类定义处添加以下变量
    private ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个线程池，可以根据需要调整


    @Override
    public String listMaterialFow() {
        RestTemplate restTemplate;
        try {
            restTemplate = TrustAllHttpsCertificates.createRestTemplate();
        } catch (Exception e) {
            throw new RuntimeException("Failed to create rest template", e);
        }

        Map<String, Object> requestBody = new HashMap<>();
        Map<String, String> inputs = new HashMap<>();
//        inputs.put("PalletCode", palletCode);
        requestBody.put("Inputs", inputs);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody);

        ResponseEntity<String> response = restTemplate.exchange(
//                "https://10.143.7.35/Apriso/httpServices/operations/IF_MES_SFSys_GetMaterialFow",
                "https://MesWebCluster.cmhijs.cn/Apriso/httpServices/operations/IF_MES_SFSys_GetMaterialFow",
                HttpMethod.POST,
                entity,
                String.class
        );
        System.out.println("======这是返回数据========");
        System.out.println(response.getBody());
        System.out.println("======这是返回数据========");

//以下是返回值为String时
        try {
            // Parse the JSON response
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> jsonMap = mapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>(){});
            Map<String, Object> outputs = (Map<String, Object>) jsonMap.get("Outputs");
            List<Map<String, Object>> outMaterialFlow = (List<Map<String, Object>>) outputs.get("OutMaterialFlow");
            //创建一个新的列表，用于存储实体对象
            List<PoschangeData> poschangeDataList = new ArrayList<>();

            //遍历outMaterialFlow列表
            for (Map<String, Object> map : outMaterialFlow) {
                String id = UUID.randomUUID().toString();
                //创建一个新的实体对象
                PoschangeData poschangeData = new PoschangeData();
                //将map中的数据赋值给实体对象
                poschangeData.setId(id);
                poschangeData.setProductNo((String) map.get("ProductNo"));
                poschangeData.setSerialNo((String) map.get("SerialNo"));
                poschangeData.setLocation((String) map.get("Location"));
                poschangeData.setToLocation((String) map.get("ToLocation"));
                poschangeData.setContainer((String) map.get("Container"));
                poschangeData.setToContainer((String) map.get("ToContainer"));
                poschangeData.setLastUpdateOn((String) map.get("LastUpdateOn"));
                poschangeData.setType((String) map.get("Type"));
                //将实体对象添加到列表中
                poschangeDataList.add(poschangeData);
                // 每当列表大小达到5000，我们就提交一个任务到线程池
                if (poschangeDataList.size() >= 5000) {
                    List<PoschangeData> batch = new ArrayList<>(poschangeDataList);
                    poschangeDataList.clear();

                    executorService.submit(() -> {
                        log.info("Task started in thread: {}", Thread.currentThread().getName());
                        poschangerecordtableDao.insertBatch(batch);
                        log.info("Task completed in thread: {}", Thread.currentThread().getName());
                    });
                }
            }
            // 如果还有剩余的数据，也提交到线程池
            if (!poschangeDataList.isEmpty()) {
                executorService.submit(() -> {
                    poschangerecordtableDao.insertBatch(poschangeDataList);
                });
            }

            // 关闭线程池
            executorService.shutdown();
            try {
                // 等待所有任务完成，或最多等待5分钟
                if (!executorService.awaitTermination(5, TimeUnit.MINUTES)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException ex) {
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
            String materialFlow = mapper.writeValueAsString(outMaterialFlow);
            JSONArray jsonArray = new JSONArray(outMaterialFlow);
            return materialFlow;
        } catch (Exception e) {
            // Handle the exception. This could involve logging the error, notifying the user, etc.
            e.printStackTrace();
            return null;
        }
    }




    @Data
    public static class  Mat{
        private String currentId;
        private String patentId;
        private String  other;
        private Date runTime;

        private String posId;

        private String empId;

        private String ename;
    }
    public void selectByMatid(String matid,List<Mat> res) {

        List<PoschangerecordtableEntity> currentMatidList = poschangerecordtableDao.selectByMatIdUpNew(matid);
        if (currentMatidList==null||currentMatidList.size()==0|| Objects.isNull(currentMatidList.get(0))){
            return;
        }
        //组装结果展示字符串
/*        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(matid).append("->的上一级物料是->");
        for (int i = 0; i < currentMatidList.size(); i++) {
            stringBuilder.append(currentMatidList.get(i));
            if (i < currentMatidList.size() - 1) {
                stringBuilder.append(",");
            }
        }
//        System.out.println(stringBuilder.toString());

        res.add(stringBuilder.toString());*/

        for (int i = 0; i < currentMatidList.size(); i++) {

           PoschangerecordtableEntity entity=currentMatidList.get(i);
       //     if (i < currentMatidList.size() - 1){
                Mat mat=new Mat();
                mat.setCurrentId(matid);
                mat.setPatentId(entity.getUpmatid());
                mat.setRunTime(entity.getLogtime());
                mat.setPosId(entity.getPosid());
                mat.setEmpId(entity.getEmpid());
                mat.setEname(entity.getEname());
                res.add(mat);
        //    }
        }

        //把结果递归
        for (PoschangerecordtableEntity pojo : currentMatidList) {
            selectByMatid(pojo.getUpmatid(),res);
        }
    }

}